package auth

import (
	"FYKJ_Admin/models/auth"
	"FYKJ_Admin/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"strings"
	"time"
)

type AuthController struct {
	beego.Controller
}
//权限管理列表
func (a *AuthController) List(){
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")
	auths := []auth.Auth{}
	//每页显示条数
	pagePerNum :=8
	//当前页
	currentPage,err := a.GetInt("page")
	//收索查询功能，入参
	kw := a.GetString("kw")
	// 偏移量
	offsetNum := pagePerNum * (currentPage - 1)
	//打印查询信息
	ret :=fmt.Sprintf("用户查询权限信息，当前页：%d;查询条件:%s",currentPage,kw)
	logs.Info(ret)

	var count int64 = 0
	if kw != "" { //有查询条件的
		// 总记录数 ,,__contains包含列
		count, _ = qs.Filter("is_delete", 0).Filter("auth_name__contains",kw).Count()
		qs.Filter("is_delete", 0).Filter("auth_name__contains",kw).Limit(pagePerNum).Offset(offsetNum).All(&auths)
	}else {
		// 总记录数
		count, _ = qs.Filter("is_delete", 0).Count()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).All(&auths)
	}
	if err != nil { //说明没有获取到当前页
		currentPage = 1
	}

	//总页数
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	// 上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}
	// 下一页
	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage {
		nextPage = countPage
	}

	page_map := utils.Paginator(currentPage, pagePerNum, count)
	a.Data["page_map"] = page_map
	a.Data["currentPage"] = currentPage
	a.Data["countPage"] = countPage
	a.Data["count"] = count
	a.Data["auths"] = auths
	a.Data["prePage"] = prePage
	a.Data["nextPage"] = nextPage
	a.Data["kw"] = kw
	a.TplName = "auth/auth_list.html"
}

//权限管理添加
func (a *AuthController) ToAdd() {
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")
	auths := []auth.Auth{}
	qs.Filter("is_delete",0).All(&auths)
	a.Data["auths"] = auths
	a.TplName ="auth/auth_add.html"
}

func (a *AuthController) DoAdd() {
	auth_parent_id,_ := a.GetInt("auth_parent_id")
	auth_name := a.GetString("auth_name")
	auth_url := a.GetString("auth_url")
	auth_desc := a.GetString("auth_desc")
	is_active,_ := a.GetInt("is_active")
	auth_weight,_ := a.GetInt("auth_weight")
	auth_icon := a.GetString("auth_icon")
	p_name := a.GetString("p_name")

	o := orm.NewOrm()
	auth_data := auth.Auth{AuthName:auth_name,UrlFor:auth_url,Pid:auth_parent_id,PName:p_name,Desc:auth_desc,IsActive:is_active,
		Weight:auth_weight,Icon:auth_icon,CreateTime:time.Now(),UpdatedTime:time.Now()}
	_,err := o.Insert(&auth_data)
	message_map := map[string]interface{}{}
	if err != nil { //说明插入数据有问题
		ret_addinfo :=fmt.Sprintf("添加权限出错，添加信息：auth_parent_id%d|p_name%s|auth_name%s|auth_url%s|auth_desc%s|" +
			"is_active%d|auth_weight%d|auth_icon%s",auth_parent_id,p_name,auth_name,auth_url,auth_desc,is_active,auth_weight,auth_icon)
		ret :=fmt.Sprintf("添加权限出错，错误信息：%v",err)
		logs.Error(ret_addinfo)
		logs.Error(ret)
		message_map["code"] = 1001
		message_map["msg"] = "添加数据出错，请重新添加！"
		a.Data["json"] = message_map
	}else {
		ret_addinfo :=fmt.Sprintf("添加权限菜单成功，添加信息：auth_parent_id%d|p_name%s|auth_name%s|auth_url%s|auth_desc%s|" +
			"is_active%d|auth_weight%d|auth_icon%s",auth_parent_id,p_name,auth_name,auth_url,auth_desc,is_active,auth_weight,auth_icon)
		logs.Info(ret_addinfo)
		message_map["code"] = 200
		message_map["msg"] = "添加权限成功！"
		a.Data["json"] = message_map
	}
	a.ServeJSON()

}


//权限批量删除
func (a *AuthController) MuliDelete() {
	ids := a.GetString("ids")
	//得到的结果"3,7,8,9",需要截取掉两边引号为 3,7,8,9
	new_ids :=ids[1:len(ids)-1]
	//，切割符号为逗号
	id_arr := strings.Split(new_ids,",")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")
	for _, v := range id_arr{
		//字符串转int64
		id_int := utils.StrToInt(v)
		qs.Filter("sys_id",id_int).Update(orm.Params{
			"is_delete":1,
		})
	}
	ret :=fmt.Sprintf("权限删除功能，批量删除成功：用户ids:%s;",ids)
	logs.Info(ret)
	a.Data["json"] = map[string]interface{}{"code":200,"msg":"批量删除成功！"}
	a.ServeJSON()
}

//权限停用启用
func (u *AuthController) IsActive() {
	is_active,_ := u.GetInt("is_active_val")
	sys_id,_ := u.GetInt("sys_id")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_active == 1 {
		qs.Update(orm.Params{
			"is_active": 2,
		})
		ret := fmt.Sprintf("权限停用/启用功能，权限id:%d,停用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "停用成功"
	}else if is_active == 2 {
		qs.Update(orm.Params{
			"is_active": 1,
		})
		ret := fmt.Sprintf("权限停用/启用功能，权限id:%d,启用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "启用成功"
	}

	u.Data["json"] = message_map
	u.ServeJSON()
}

//编辑权限信息
func (u *AuthController) ToUpdate() {
	sys_id,_ := u.GetInt64("sys_id")
	o := orm.NewOrm()
	//定义一个容器
	auth_data := auth.Auth{}
	o.QueryTable("sys_auth").Filter("sys_id",sys_id).One(&auth_data)
	u.Data["auth"] =auth_data
	u.TplName = "auth/auth_edit.html"
}

func (u *AuthController) DoUpdate() {
	sys_id,_ := u.GetInt64("sys_id")
	auth_name := u.GetString("auth_name")
	url_name := u.GetString("url_name")
	pid_name := u.GetString("pid_name")
	pid,_ := u.GetInt("pid")
	weight,_ := u.GetInt("weight")
	desc := u.GetString("desc")
	icon := u.GetString("icon")
	is_active,_ := u.GetInt("is_active")

	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}

		_,err := qs.Update(orm.Params{
			"auth_name" : auth_name,
			"url_for" : url_name,
			"p_name" : pid_name,
			"pid" : pid,
			"weight" : weight,
			"desc" : desc,
			"icon" : icon,
			"is_active" : is_active,
		})

		if err != nil {
			ret := fmt.Sprintf("编辑权限功能，错误信息，auth_name:%s|url_name:%s|pid:%d|pid_name%s|weight:%d" +
				"|desc:%s|icon:%s|is_active%d",auth_name,url_name,pid,pid_name,weight,desc,icon,is_active)
			logs.Error(ret)
			message_map["code"] = 10001
			message_map["msg"] = "更新失败"
		}else {
			ret := fmt.Sprintf("编辑权限功能，错误信息，auth_name:%s|url_name:%s|pid:%d|pid_name%s|weight:%d" +
				"|desc:%s|icon:%s|is_active%d",auth_name,url_name,pid,pid_name,weight,desc,icon,is_active)
			logs.Info(ret)
			message_map["code"] = 200
			message_map["msg"] = "更新成功"
		}

	u.Data["json"] = message_map
	u.ServeJSON()

}

//删除权限
func (u *AuthController) Delete() {
	sys_id,_ := u.GetInt64("sys_id")
	is_delete_val,_ := u.GetInt("is_delete_val")
	o :=orm.NewOrm()
	// 直接delete删除物理删除
	//o.QueryTable("sys_user").Filter("SysId",SysId).Delete()
	//逻辑删除，修改状态
	qs := o.QueryTable("sys_auth").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_delete_val ==0 {
		qs.Update(orm.Params{
			"is_delete": 1,
		})
		ret := fmt.Sprintf("权限删除功能，权限id:%d,删除成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "删除成功！"
	}
	u.Data["json"] = message_map
	u.ServeJSON()
	// 重定向页面（刷新页面）
	//u.Redirect(beego.URLFor("UserController.List"),302)
}